import urllib
import re
import optparse

CURRENT_PRICE_URL = "http://tw.stock.yahoo.com/q/q?s=%d"
BONUS_HISTORY_URL = "http://tw.stock.yahoo.com/d/s/dividend_%d.html"
STOCK_LIST_FILE = "list.txt"
DEFAULT_CASH_RATE = 16

def getPrice(id):
	handle = urllib.urlopen(CURRENT_PRICE_URL % id)
	for line in handle.readlines():
		if "</b></td>" in line:
			r = re.search(r"[0-9]+\.[0-9]+", line)
			return float(r.group())

def getBonus(id, years=5):
	handle = urllib.urlopen(BONUS_HISTORY_URL % id)
	html_src = handle.readlines()
	
	count = 0
	result = []
	for i, line in enumerate(html_src):
		if "<tr bgcolor=\"#FFFFFF\">" in line:
			bonus_line = html_src[i+2]
			bonus_search = re.search(r"[0-9]+.[0-9]+", bonus_line)
			result.append(float(bonus_search.group()))
			count += 1
		
		if count == years:
			break
	
	return result

def getStockList(filename):
	stock_list = []
	
	f = open(filename, "r")
	try:
		for line in f.readlines():
			if line and line[0] == "\n":
				continue
			
			result = re.split("[ \n]+", line)
			stock_list.append(int(result[0]))
	except:
			f.close()
			raise "open file fail !!"	
	f.close()
	
	return stock_list

def report(id_list, rate=DEFAULT_CASH_RATE):
	print "%6s%6s%6s%6s%6s%6s%6s%8s%8s" % ("id", "100", "99", "98", "97", "96", "avg", "ref", "price")
	for id in id_list:
		price = getPrice(id)
		bonus = getBonus(id, 5)
		avg = sum(bonus) / len(bonus)
		ref_price = avg * rate
		mark = "*" if price < ref_price else ""
		
		print "%6s%6.2f%6.2f%6.2f%6.2f%6.2f%6.2f%8.2f%8.2f%2s" % (id, bonus[0], bonus[1], bonus[2], bonus[3], bonus[4], avg, ref_price, price, mark)


def main():
	opt = optparse.OptionParser(usage="%prog [options]")
	opt.add_option("-r", "--rate", action="store", type="int", default=DEFAULT_CASH_RATE, help="current price / cash bonus (default: %d)" % (DEFAULT_CASH_RATE))
	(options, args) = opt.parse_args()
	
	stock_list = getStockList(STOCK_LIST_FILE)
	report(stock_list, options.rate)

if __name__ == "__main__":
	main()